import router from './router'
import { stores } from '@/stores/index.js'
import { ElMessage, ElLoading } from 'element-plus'
import { http } from '@/utils/index.js'

const whiteList = ['/login', 'not-found', '/policeInfor/release', '/policeInfor/add']
router.beforeEach(async (to, from, next) => {
  console.log(router)
  const userStore = stores.useUserStore()

  //不是免登录跳转，没有token, 也不是跳转到白名单页面，则强制跳转到登录页面
  if (!to.query.pkiNo && userStore.token == '' && (!whiteList.includes(to.path) || !whiteList.includes(to.name)) && to.path != '/login') {
    console.log(11111)
    next({ path: '/login' })
  } else {
    //  免登录跳转
    if (to.query.pkiNo) {
      console.log(222222)
      // menuStore.isShowMenu = false

      const loadingInstance = ElLoading.service()
      // const res = await userStore.getUserInfor(decodeURIComponent(to.query.token))
      const res = await http('/znjszd3/ht/login', 'post', {
        pkiNo: to.query.pkiNo
      })
      if (res.status == 200) {
        userStore.setToken(res.data.token)
        userStore.setUserInfor(res.data.sysLoginUser)
        router.push({
          path: to.path
        })
      } else {
        ElMessage.error(res.message[0])
        userStore.clearUserInfor()
        router.push('/login')
      }
      loadingInstance.close()
    } else {
      const menuStore = stores.useMenuStore()
      //是否有权限访问该路由
      const isVisitable = checkVisitable(to, menuStore.leftMenu)
      if (whiteList.includes(to.path) || whiteList.includes(to.name)) {
        next()
      } else if (isVisitable) {
        next()
      } else {
        next({ path: '/login' })
        // next({
        //   name: 'not-found'
        // })
      }
    }
  }
})
//是否有权限访问当前路由
function checkVisitable(to, routes) {
  console.log(to)
  let result = false
  if (to.path == '/login') {
    result = true
  } else {
    // console.log(to.meta.title)
    // console.log(routes)
    toFind(to.meta.title, routes)
    function toFind(title, routes) {
      routes.find((item) => {
        if (item.children && item.children.length > 0) {
          toFind(title, item.children)
        } else {
          if (title == item.meta.title) {
            result = true
            return
          }
        }
      })
    }
  }
  // console.log(result)
  return result
}
